/*
 * @Author: vera_min vera_min@163.com
 * @Date: 2024-12-30 11:03:41
 * @LastEditors: vera_min vera_min@163.com
 * @LastEditTime: 2025-01-08 11:00:46
 * @FilePath: /mail-project/src/directive/draggable.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import type { App, Directive } from 'vue';
interface ElType extends HTMLElement {
  parentNode: any;
}

const draggable: Directive = {
  mounted: function (el: ElType) {
    // el.style.cursor = 'move';
    el.style.position = 'absolute';

    el.onmousedown = function (e) {
      if(isDisableDraggable(e, el)) return;
      let disX = e.pageX - el.offsetLeft;
      let disY = e.pageY - el.offsetTop;

      disX = e.pageX - el.offsetLeft;
      disY = e.pageY - el.offsetTop;

      document.onmousemove = function (e) {
        // if(isDisableDraggable(e)) return;
        let x = e.pageX - disX;
        let y = e.pageY - disY;

        let maxX = window.innerWidth - el.offsetWidth;
        let maxY = window.innerHeight - el.offsetHeight;

        if (x < 0) {
          x = 0;
        } else if (x > maxX) {
          x = maxX;
        }

        if (y < 0) {
          y = 0;
        } else if (y > maxY) {
          y = maxY;
        }
        
        el.style.left = x + 'px';
        el.style.top = y + 'px';
      };

      document.onmouseup = function () {
        document.onmousemove = document.onmouseup = null;

      };
      document.onmouseenter = function () {
        document.onmousemove = document.onmouseup = null;

      };
    };
  }
}

const isDisableDraggable = (e:any, el: Element) => {
  // 获取目标元素
  var elements:any = el.getElementsByClassName('box-header');
  if (!elements.length) return true;
  // 获取元素的位置和大小
  var rect = elements[0].getBoundingClientRect();
  // 判断鼠标是否在元素内
  var isWithinElement = e.clientX >= rect.left && e.clientX <= rect.right && e.clientY >= rect.top && e.clientY <= rect.bottom;
  // 根据条件执行操作
  if (isWithinElement) {
    return false;
  } else {
    return true;
  }
}

// 在Vue应用中注册全局自定义指令
export const installGlobalDraggableDirectives = (app: App) => {
  app.directive('draggable', draggable);
};

